package com.bifrost.service.impl;

import com.bifrost.cbentity.SapContractProduct;
import com.bifrost.cbrepository.SapContractProductRepository;
import com.bifrost.service.SapContractProductService;
import com.bifrost.util.LocalDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author Lee
 * Create Class on 2018/7/26
 * @com.bifrost.service
 * @wechat-mall
 */
@Service
public class SapContractProductServiceImpl implements SapContractProductService{

    @Autowired
    SapContractProductRepository contractProductRepository;

    @Override
    public SapContractProduct verifyContract(String externalId, String storeCode, Date activeEndDate) {
        if(activeEndDate==null){activeEndDate = new Date();}
        LocalDate dateTime = LocalDateUtils.fromDate(activeEndDate);

        List<SapContractProduct> sapContractProducts = contractProductRepository.findAllByMatnrAndWerksAndDelbsIsNull(externalId, storeCode);
        if(sapContractProducts.isEmpty()){
            Assert.notEmpty(sapContractProducts,"柜号不存在.");
        }
        // 最后创建的柜号
        sapContractProducts.sort((o1, o2) -> o2.getNoid().compareTo(o1.getNoid()));
        SapContractProduct contractProduct = sapContractProducts.get(0);

        LocalDate startDate = LocalDate.parse(contractProduct.getDatab(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate endDate = LocalDate.parse(contractProduct.getDatbi(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        Assert.isTrue((dateTime.isBefore(endDate) && dateTime.isAfter(startDate)),"活动日期不在柜号有效期内");

        return contractProduct;
    }
}
